package com.kiseny.main;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.common.util.Constants;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;

public class DownloadFromYunbei {

	private static final String destFileName = "D:/svn2/shop2011/doc/dest.properties";
	private static final String dataPath = "D:/svn2/morgan0329/doc2/yunbei/";

	private static final String mainURL = "http://www.yunbei.com/";
	private static final String daixiaoURL = "daixiao_jia.htm?id=";
	private static final String productURL = "product.htm?id=";

	private static final String KEY_WORD_CATEGORY = "category";
	private static final String KEY_WORD_YUNBEI = "yunbei";

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {

		Properties prop = new Properties();
		prop.load(new FileReader(destFileName));

		// The Firefox driver supports javascript.
		WebDriver driver = new FirefoxDriver();
		driver.get(mainURL);

		// Enter username and password.
		driver.findElement(By.name("username")).sendKeys("morgan0329");
		driver.findElement(By.name("password")).sendKeys("24137569");
		driver.findElement(By.name("passcode")).sendKeys("6759");

		List<WebElement> eleButtons = driver.findElements(By.className("anniuso"));
		eleButtons.get(1).click();

		Map<String, String> categoryMap = new HashMap<String, String>();
		Map<String, String> yunbeiMap = new HashMap<String, String>();
		Enumeration enums = prop.keys();
		while (enums.hasMoreElements()) {
			Object key = enums.nextElement();
			if (((String) key).startsWith(KEY_WORD_CATEGORY)) {
				categoryMap.put((String) key, (String) prop.get(key));
			}

			if (((String) key).startsWith(KEY_WORD_YUNBEI)) {
				yunbeiMap.put((String) key, (String) prop.get(key));
			}
		}

		for (String category : categoryMap.keySet()) {
			String lastWordInCA = category.replace(KEY_WORD_CATEGORY, "");

			for (String yunbei : yunbeiMap.keySet()) {
				String lastWordInYun = yunbei.replace(KEY_WORD_YUNBEI, "");

				if (lastWordInYun.startsWith(lastWordInCA)) {
					File file = new File(dataPath + categoryMap.get(category)
							+ Constants.MARKS_DASH + (String) prop.get(yunbei));
					if (!file.isDirectory()) {
						file.mkdirs();
					}

					driver.get(mainURL);
					driver.findElement(By.linkText((String) prop.get(yunbei))).click();

					List<WebElement> eleProducts = driver.findElements(By
							.className("pro_lipic"));

					List<String> ids = new ArrayList<String>();
					for (WebElement webElement : eleProducts) {
						String hrefValue = webElement.findElement(
								By.tagName("a")).getAttribute("href");
						ids.add(hrefValue.replace("/" + productURL, ""));
					}

					String subFolderName = dataPath + categoryMap.get(category)
							+ Constants.MARKS_DASH + (String) prop.get(yunbei) + "/";

					for (String id : ids) {
						driver.get(mainURL + productURL + id);

						List<WebElement> attrbutes0 = driver.findElements(By.className("pro_jiage_li2"));
						List<WebElement> attrbutes1 = driver.findElements(By.className("pro_jiage_li3"));
						List<WebElement> attribute3 = driver.findElements(By.className("pro_sm_li"));
						WebElement attribute04 = driver.findElement(By.className("font18"));

						String txtFileName = subFolderName + id
								+ attrbutes0.get(0).getText().replace(" ", "")
								+ ".txt";

						String attributes05Value = attribute3.get(0).findElement(By.tagName("span")).getText();
						
						//Product Name in Chinese
						String firstValue = filterYB(attrbutes0.get(0).getText());
						//Product Code
						String secondValue = filterUnit(attrbutes1.get(0).getText());
						//Product Weight
						String thirdValue = filterUnit(attrbutes0.get(1).getText());
						//Details in Chinese
						String fourthValue = filterDetail01(attributes05Value);
						//View Times
					    String fifthValue = filterUnit(attrbutes1.get(1).getText());
					   //Wholesale Price: 
						String sixthValue = filterUnit(attribute04.getText());

						File txtFile = new File(txtFileName);
						if (!txtFile.exists()) {
							txtFile.createNewFile();
						}

						OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(txtFile), "UTF-8");
						BufferedWriter bufferedWriter = new BufferedWriter(write);

						bufferedWriter.write("ViewTimes=" + fifthValue + Constants.MARKS_WIN_LF);
						bufferedWriter.write("WholesalePrice=" + sixthValue + "RMB\r\n\r\n");
						
						bufferedWriter.write("ProductNameCN=" + firstValue + "\r\n");
						bufferedWriter.write("ProductCode=" + secondValue + "\r\n");
						bufferedWriter.write("ProductWeight=" + thirdValue + "\r\n");
						bufferedWriter.write("DetailsCN=" + fourthValue + "\r\n\r\n");
						 
						List<String> moreDetailsCN = getMoreCN(fourthValue);
						if (moreDetailsCN.size() > 0) {
							for (String detailCN : moreDetailsCN) {
								bufferedWriter.write(detailCN + "\r\n");
							}
						}
						bufferedWriter.write("\r\n");

						List<String> finalPrices = getFinalPrices(Float.parseFloat(sixthValue));
						
						for (String finalPrice : finalPrices) {
							bufferedWriter.write(finalPrice + "USD\r\n");
						}
						bufferedWriter.write("\r\n");

						Translate.setHttpReferrer(mainURL + productURL + id);
						//firstValue: Product Name
						bufferedWriter.write("ProductNameEN=" 
								+ Translate.execute(firstValue, Language.CHINESE_SIMPLIFIED, Language.ENGLISH) 
								+ "\r\n");
						
						String fourthValueEN = Translate.execute(fourthValue, Language.CHINESE_SIMPLIFIED, Language.ENGLISH);
						
						bufferedWriter.write("DetailsEN=" + fourthValueEN +  "\r\n\r\n");
						 
						List<String> moreDetailsEN = getMoreEN(fourthValueEN);
						if (moreDetailsEN.size() > 0) {
							for (String detailEN : moreDetailsEN) {
								bufferedWriter.write(detailEN + "\r\n");
							}
						}
						bufferedWriter.write("\r\n");

						bufferedWriter.write("taobaoPrice=" + getTaobaoPrice(Float.parseFloat(sixthValue)) + "RMB\r\n\r\n");
						
						//Write them for DHGate
						bufferedWriter.write("ProductGroup=Handicraft article" + "\r\n");
						bufferedWriter.write("PackageLength=" + "\r\n" );
						bufferedWriter.write("PackageWidth=" + "\r\n" );
						bufferedWriter.write("PackageHeight=" + "\r\n");

						//default is 5 * productWeight
						bufferedWriter.write("PackageWeight=" + getPackageWeight(thirdValue) + "\r\n");
						//default is 90 Days
						bufferedWriter.write("ValidityPeriod=90Days" + "\r\n");

						bufferedWriter.write("ProductName=" + "\r\n" );
						bufferedWriter.write("Material=" + "\r\n" );
						bufferedWriter.write("Specifications=" + "\r\n" );
						bufferedWriter.write("Details=" + "\r\n\r\n" );

						bufferedWriter.close();

						downloadPicture(id,driver, prop, subFolderName);
					}

				}
			}

		}
		driver.close();

	}
	
	/**
<= 10RMB                 * 3
quantity 1-2             * 3
         3-10            * 2.95
         11-30           * 2.90
         31-100          * 2.85
         100-199         * 2.80
10< x <=20RMB            * 2.5
quantity 1-2             * 2.5
         3-10            * 2.45
         11-30           * 2.40
         31-100          * 2.35
         100-199         * 2.30
20< x <9999RMB           * 2
quantity 1-2             * 2.0
         3-10            * 1.95
         11-30           * 1.90
         31-100          * 1.85
         100-199         * 1.80
         
     exchangeRate=6.557  USD/RMB
     
     1 set = 5 pieces
     
	 * @param originalPrice
	 * @return finalPrice
	 */
	private static List<String> getFinalPrices(float originalPrice) {

		List<String> stringList = new ArrayList<String>();
		
		float tempPrice = originalPrice * 5;

		if (originalPrice <= 10) {
			stringList.add(getResult("1-2=", tempPrice * 3));
			stringList.add(getResult("3-10=", tempPrice * 2.95));
			stringList.add(getResult("11-30=", tempPrice * 2.90));
			stringList.add(getResult("31-100=", tempPrice * 2.85));
			stringList.add(getResult("101-199=", tempPrice * 2.80));
			
		} else if (originalPrice > 10 && originalPrice <= 20) {
			stringList.add(getResult("1-2=", tempPrice * 2.5));
			stringList.add(getResult("3-10=", tempPrice * 2.45));
			stringList.add(getResult("11-30=", tempPrice * 2.40));
			stringList.add(getResult("31-100=", tempPrice * 2.35));
			stringList.add(getResult("101-199=", tempPrice * 2.30));
			
		} else {
			stringList.add(getResult("1-2=", tempPrice * 2.00));
			stringList.add(getResult("3-10=", tempPrice * 1.95));
			stringList.add(getResult("11-30=", tempPrice * 1.90));
			stringList.add(getResult("31-100=", tempPrice * 1.85));
			stringList.add(getResult("101-199=", tempPrice * 1.80));
		}
		
		return stringList;
	}
	
	private static String getResult(String propertyName, double price) {
		
		DecimalFormat format001 = new DecimalFormat("#####0.00");
		return propertyName + format001.format((price)/6.557);
	}

	
	/**
	<= 10RMB                 * 2

	10< x <=20RMB            * 1.8

	20< x <9999RMB           * 1.6
	     
		 * @param originalPrice
		 * @return taobaoPrice
		 */
		private static String getTaobaoPrice(float originalPrice) {
			DecimalFormat format001 = new DecimalFormat("#####0.00");
			String taobaoPrice = null;

			if (originalPrice <= 10) {
				taobaoPrice = format001.format(originalPrice * 2);
				
			} else if (originalPrice > 10 && originalPrice <= 20) {
				taobaoPrice = format001.format(originalPrice * 1.8);

			} else {
				taobaoPrice = format001.format(originalPrice * 1.6);
			}
			
			return taobaoPrice;
		}
		
		private static String getPackageWeight(String productWeight) {
			DecimalFormat format001 = new DecimalFormat("#####0.00");
			
			String weightWOUnit = productWeight.replace("Grams", "");
			float  pacakgeWeightWOUnit = Float.parseFloat(weightWOUnit) * 5;

			return format001.format(pacakgeWeightWOUnit/1000) + "Kilograms";
		}
		
		private static void downloadPicture (String id, WebDriver driver, Properties prop, String subFolderName)
		    throws Exception {
			driver.get(mainURL + daixiaoURL + id);
			List<WebElement> eleImages = driver.findElements(By.tagName("iframe"));

			for (int i = 0; i < eleImages.size(); i++) {
				Runtime.getRuntime().exec(
						(String) prop.get("downloadTool") + " "
								+ eleImages.get(i).getAttribute("src") + " "
								+ subFolderName + "/" + id + Constants.MARKS_DASH + i + ".jpg");
			}
		}
		
		private static String filterYB(String string) {
			return string.replace(" ", "").replace("云贝", "Kiseny");
		}
		
	    private static String filterUnit(String string) {
	    	return string.replace(" ", "")
	    	    .replace("#", "")
	    	    .replace("克", "Grams")
	    	    .replace("次", "Times");
	    }
	    
	    private static String filterDetail01(String string) {
	    	return StringUtils.trim(string)
	    	    .replace("云贝", "Kiseny").replace("\n", "BLANK");
	    }
	    
	    private static List<String> getMoreCN(String string) {
	    	
	    	List<String> detailList = new ArrayList<String>();
	    	
	    	String[] splits = string.split("BLANK");
	    	
	    	for (String split : splits) {
	    		split = StringUtils.trim(split).replace("：", ":");
	    		
	    		if (split.startsWith("材质:") || split.startsWith("【材质】")) {
	    			detailList.add(split.replace("材质:", "MaterialCN=")
	    					            .replace("【材质】", "MaterialCN="));
	    		}
	    		if (split.startsWith("备注:") || split.startsWith("【备注】")) {
	    			detailList.add(split.replace("备注:", "NotesCN=")
	    					            .replace("【备注】", "NotesCN="));
	    		}
	    		if (split.startsWith("材料:") || split.startsWith("【材料】")) {
	    			detailList.add(split.replace("材料:", "MaterialCN=")
	    					            .replace("【材料】", "MaterialCN="));
	    		}
	    		if (split.startsWith("规格:") || split.startsWith("【规格】")) {
	    			detailList.add(split.replace("规格:", "SpecificationsCN=")
	    					            .replace("【规格】", "SpecificationsCN="));
	    		}
	    	}

	    	return detailList;
	    }
	    
	    private static List<String> getMoreEN(String string) {
	    	
	    	List<String> detailList = new ArrayList<String>();
	    	String[] splits = string.split("BLANK");
	    	
	    	for (String split : splits) {
	    		split = StringUtils.trim(split).replace("：", ":");
	    		
	    		if (StringUtils.contains(split, "specifications:") || StringUtils.contains(split, "Specifications:") || StringUtils.contains(split, "【Specification】")) {
	    			split = split.replace("specifications:", "SpecificationsEN=")
		                .replace("Specifications:", "SpecificationsEN=")
		                .replace("【Specification】", "SpecificationsEN=");
	    			detailList.add(StringUtils.substringAfter(split, "SpecificationsEN="));
	    		}
	    		if (StringUtils.contains(split, "specification:") || StringUtils.contains(split, "Specification:") || StringUtils.contains(split, "【Specifications】")) {
	    			split = split.replace("specification:", "SpecificationsEN=")
	    					            .replace("Specification:", "SpecificationsEN=")
	    					            .replace("【Specifications】", "SpecificationsEN=");
	    			detailList.add(StringUtils.substringAfter(split, "SpecificationsEN="));
	    		}
	    		
	    		if (StringUtils.contains(split, "materials:") || StringUtils.contains(split, "Materials:") || StringUtils.contains(split, "【Materials】")) {
	    			split = split.replace("materials:", "MaterialEN=")
	    					            .replace("Materials:", "MaterialEN=")
	    					            .replace("【Materials】", "MaterialEN=");
	    			detailList.add(StringUtils.substringAfter(split, "MaterialEN="));
	    		}
	    		if (StringUtils.contains(split, "material:") || StringUtils.contains(split, "Material:") || StringUtils.contains(split, "【Material】")) {
	    			split = split.replace("material:", "MaterialEN=")
	    					            .replace("Material:", "MaterialEN=")
	    					            .replace("【Material】", "MaterialEN=");
	    			detailList.add(StringUtils.substringAfter(split, "MaterialEN="));
	    		}
	    		
	    		if (StringUtils.contains(split, "notes:") || StringUtils.contains(split, "Notes: ") || StringUtils.contains(split, "【Notes】")) {
	    			split = split.replace("notes:", "NotesEN=")
	    					            .replace("Notes:", "NotesEN=")
	    					            .replace("【Notes】", "NotesEN=");
	    			detailList.add(StringUtils.substringAfter(split, "NotesEN="));
	    		}
	    		if (StringUtils.contains(split, "note:") || StringUtils.contains(split, "Note:") || StringUtils.contains(split, "【Note】")) {
	    			split = split.replace("note:", "NotesEN=")
	    					            .replace("Note:", "NotesEN=")
	    					            .replace("【Note】", "NotesEN=");
	    			detailList.add(StringUtils.substringAfter(split, "NotesEN="));
	    		}
	    		
	    		if (StringUtils.contains(split, "sizes: ") || StringUtils.contains(split, "Sizes:") || StringUtils.contains(split, "【Sizes】 ")) {
	    			split = split.replace("sizes:", "SizeEN=")
	    					            .replace("Sizes:", "SizeEN=")
	    					            .replace("【Sizes】", "SizeEN=");
	    			detailList.add(StringUtils.substringAfter(split, "SizeEN="));
	    		}
	    		if (StringUtils.contains(split, "size:") || StringUtils.contains(split, "Size:") || StringUtils.contains(split, "【Size】 ")) {
	    			split = split.replace("size:", "SizeEN=")
	    					            .replace("Size:", "SizeEN=")
	    					            .replace("【Size】", "SizeEN=");
	    			detailList.add(StringUtils.substringAfter(split, "SizeEN="));
	    			
	    		}
	    	}

	    	return detailList;
	    }
}